package com.xxjh.auth.common.encryption;

import com.alibaba.fastjson2.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.xxjh.auth.common.dto.LoginUserInfo;
import com.xxjh.auth.common.enums.ResultCode;
import com.xxjh.auth.common.exceptions.ConditionException;
import sun.security.provider.certpath.OCSPResponse;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import static com.xxjh.auth.common.encryption.EncryptionConstants.AUTHORIZATION;
import static com.xxjh.auth.common.encryption.EncryptionConstants.DEFAULT_EXPIRE_DAY;


/**
 * @author CHENCHEN
 * @title a
 * @company 新兴际华科技（天津）有限公司
 * @create 2024-07-03 19:21
 */
public class TokenParseUtil {

    private static final String ISSUER = "签发者";

    /**
     * 生成Token
     * @param loginUserInfo
     * @return
     * @throws Exception
     */
    public static String generateToken(LoginUserInfo loginUserInfo) throws Exception {
        Algorithm algorithm = Algorithm.RSA256(RSAUtil.getPublicKey(), RSAUtil.getPrivateKey());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DATE, DEFAULT_EXPIRE_DAY);
        return JWT.create()
                .withClaim(AUTHORIZATION, JSON.toJSONString(loginUserInfo))
                .withIssuer(ISSUER)
                .withExpiresAt(calendar.getTime())
                .sign(algorithm);
    }

    /**
     * 解析token获取LoginUserInfo对象
     * @param token
     * @return
     * @throws Exception
     */
    public static LoginUserInfo parseUserInfoFromToken(String token) {
        try{
            Algorithm algorithm = Algorithm.RSA256(RSAUtil.getPublicKey(), RSAUtil.getPrivateKey());
            JWTVerifier jwtVerifier = JWT.require(algorithm).build();
            DecodedJWT jwt = jwtVerifier.verify(token);
            Map<String, Claim> claims = jwt.getClaims();
            return JSON.parseObject(claims.get(AUTHORIZATION).asString(), LoginUserInfo.class);
        }catch (JWTVerificationException e){
            throw new ConditionException(ResultCode.AUTHORIZED_TIMEOUT);
        } catch (Exception e) {
            throw new ConditionException(ResultCode.UNAUTHORIZED);
        }
    }
}
